package com.lagou.sqlSession;

import com.lagou.cofig.BoundSql;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import lagou.io.pojo.Configuration;
import lagou.io.pojo.MappedStagement;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStagement mappedStagement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
       
       //注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql语句。//转换sql语句：对于#{}里边的值进行解析存储。
        String sql = mappedStagement.getSql();
        BoundSql boudnSql =  getBondSql(sql);
       //获取与预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boudnSql.getSqlText());
        //设置参数
        //执行sql
        //返回结果集
        String paramterType = mappedStagement.getParamterType();
        String resultType = mappedStagement.getResultType();
        Class<?> classType = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boudnSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {

            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = classType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);

        }
        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        Class<?> resultClass = getClassType(resultType);


        ArrayList<E> resultList = new ArrayList<>();
        //封装结果集
        while (resultSet.next()){
            Object o1= resultClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <=metaData.getColumnCount() ; i++) {
                //字段名

                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);
                //通过反射或者内省来完成对象的封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o1,object);
            }
            resultList.add((E) o1);
        }

        return resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStagement mappedStagement, Object... params) throws Exception {
        //注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql语句。//转换sql语句：对于#{}里边的值进行解析存储。
        String sql = mappedStagement.getSql();
        BoundSql boudnSql =  getBondSql(sql);
        //获取与预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boudnSql.getSqlText());
        //设置参数
        //执行sql

        String paramterType = mappedStagement.getParamterType();
        Class<?> classType = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boudnSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = classType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setString(i+1, (String) o);

        }
        int i = preparedStatement.executeUpdate();
        return i;


    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType!=null){
            Class<?> aClass = Class.forName(paramterType);
        return aClass;
        }
        return null;
    }

    private BoundSql getBondSql(String sql) {
    //标记处理类
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
       //标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse,parameterMappings);
        return boundSql;
    }


}
